//
//  TestWare.m
//  ProjectDemo
//
//  Created by IOS3 on 2018/12/19.
//  Copyright © 2018 IOS3. All rights reserved.
//

#import "TestWare.h"




@interface TestWare ()

@property (nonatomic, strong) CADisplayLink *waveDisplaylink;

@property (nonatomic, strong) CAShapeLayer  *firstWaveLayer;
@property (nonatomic, strong) CAShapeLayer  *secondWaveLayer;


@end

@implementation TestWare


- (void)startWave {
    
    self.firstWaveLayer = [CAShapeLayer layer];
    self.firstWaveLayer.frame = self.bounds;
    self.firstWaveLayer.fillColor = self.firstWaveColor.CGColor;
    [self.layer addSublayer:self.firstWaveLayer];
    
    self.secondWaveLayer = [CAShapeLayer layer];
    self.secondWaveLayer.frame = self.bounds;
    self.secondWaveLayer.fillColor = self.secondWaveColor.CGColor;
    [self.layer addSublayer:self.secondWaveLayer];
    
    self.waveDisplaylink = [CADisplayLink displayLinkWithTarget:self selector:@selector(drawPath)];
    [self.waveDisplaylink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)drawPath {
    
    CGSize frameSize = self.frame.size;
    CGFloat startY = frameSize.height - self.waveHeight;
    static double i = 0;
    
    CGFloat A = 10.f;//A振幅
    CGFloat k = startY;//y轴偏移
    CGFloat ω = 0.02;//角速度ω变大，则波形在X轴上收缩（波形变紧密）；角速度ω变小，则波形在X轴上延展（波形变稀疏）。不等于0
    CGFloat φ = 0 + i;//初相，x=0时的相位；反映在坐标系上则为图像的左右移动。
    
    CGMutablePathRef path1 = CGPathCreateMutable();
    CGMutablePathRef path2 = CGPathCreateMutable();
    CGPathMoveToPoint(path1, nil, 0, startY);
    CGPathMoveToPoint(path2, nil, 0, startY);
    
    
    for (float x = 0.0f; x <= frameSize.width ; x++) {
        CGFloat y1 = A * sin(ω*x+φ)+k;
        CGPathAddLineToPoint(path1, nil, x, y1);
        
        CGFloat y2 = A * cos(ω*x+φ)+k;
        CGPathAddLineToPoint(path2, nil, x, y2);
    }
    CGPathAddLineToPoint(path1, nil, frameSize.width, frameSize.height);
    CGPathAddLineToPoint(path1, nil, 0, self.frame.size.height);
    CGPathCloseSubpath(path1);
    CGPathAddLineToPoint(path2, nil, frameSize.width, frameSize.height);
    CGPathAddLineToPoint(path2, nil, 0, self.frame.size.height);
    CGPathCloseSubpath(path2);
    
    self.firstWaveLayer.path = path1;
    self.secondWaveLayer.path = path2;
    CGPathRelease(path1);
    CGPathRelease(path2);
    
    i += 0.1;
    if (i > M_PI * 2) {
        i = 0;//防止i越界
    }
}


- (void)stopWave {
    [self.waveDisplaylink invalidate];
    self.waveDisplaylink = nil;
    self.firstWaveLayer = nil;
    self.secondWaveLayer = nil;
    [self removeFromSuperview];
}

@end
